//
//  EFengVideoPlayerViewController.m
//  WZEfengAndEtong
//
//  Created by 李旭 on 16/9/2.
//  Copyright © 2016年 wanzhao. All rights reserved.
//

#import "EFengVideoPlayerViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface EFengVideoPlayerViewController ()
@property (strong, nonatomic) AVPlayer *player;
@property (strong, nonatomic) AVPlayerLayer *playerLayer;
@property (strong, nonatomic) AVPlayerItem *playerItem;
@end

@implementation EFengVideoPlayerViewController
-(void)setVideoFileURL:(NSURL *)videoFileURL
{
    _videoFileURL = videoFileURL;
    [self initPlayLayer];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(avPlayerItemDidPlayToEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
}
- (void)initPlayLayer
{
    AVAsset *movieAsset = [AVURLAsset URLAssetWithURL:_videoFileURL options:nil];
    self.playerItem = [AVPlayerItem playerItemWithAsset:movieAsset];
    self.player = [AVPlayer playerWithPlayerItem:_playerItem];
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
    self.playerLayer.backgroundColor = [UIColor blackColor].CGColor;
    _playerLayer.frame = self.view.bounds;
    _playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    [self.view.layer addSublayer:_playerLayer];
}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.player play];
}

-(void)show
{
    UIWindow * window = [UIApplication sharedApplication].windows.lastObject;
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    [window.rootViewController presentViewController:self animated:YES completion:nil];
}
-(void)avPlayerItemDidPlayToEnd:(NSNotification*)notificaiton
{
    if ((AVPlayerItem *)notificaiton.object != _playerItem) {
        return;
    }
    [_playerItem seekToTime:kCMTimeZero];
    [self.player play];

}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.player pause];
    [self dismissViewControllerAnimated:YES completion:nil];
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
}
@end
